package ru.stepanovdn.trading.server.strategy

import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.stream.Collectors

@Service
class StrategySelector {

    private val log = LoggerFactory.getLogger(javaClass)

    var allStrategies: List<AInstrumentByFiatStrategy>? = null
    var activeStrategies: List<AInstrumentByFiatStrategy>? = null

    val figiesForActiveStrategies: Set<String>
        get() = activeStrategies!!.stream()
            .flatMap<String> { s: AStrategy -> s.figies.keys.stream() }
            .collect(Collectors.toSet())

    fun suitableByFigi(figi: String?): List<AInstrumentByFiatStrategy> {
        return activeStrategies!!.stream()
            .filter(AInstrumentByFiatStrategy::isEnabled)
            .filter{s: AInstrumentByFiatStrategy -> s.isSuitableByFigi(figi)}
            .collect(Collectors.toList())
    }

    fun isEnabled(name: String?, figi: String?): Boolean {
        return activeStrategies!!.stream()
            .filter{s: AStrategy -> s.name == name}
            .filter{s: AStrategy -> figi == null || s.isSuitableByFigi(figi)}
            .map(AStrategy::isEnabled)
            .findFirst().orElse(false)
    }

    fun getStrategyType(name: String?, defaultValue: AStrategy.Type): AStrategy.Type {
        return allStrategies!!.stream()
            .filter { s: AStrategy -> s.name == name }
            .findFirst().map<AStrategy.Type>(AStrategy::type).orElse(defaultValue)
    }

    @PostConstruct
    private fun init() {

        allStrategies = listOf(BuyP10AndTP1PercentAndSL3PercentStrategy())

        activeStrategies = allStrategies!!.stream()
            .filter(AStrategy::isEnabled)
            .peek { s: AStrategy ->
                if (s.type === AStrategy.Type.instrumentByFiat && s.figies.isEmpty()) {
                    throw UnsupportedOperationException("Incorrect count of figies in " + s.name)
                }
            }
            .peek { s: AStrategy ->
                log.info(
                    "Enabled strategy: {}: {}",
                    s.name,
                    s.figies.keys
                )
            }
            .collect(Collectors.toList())
    }
}
